// pages/profile/profile.js
import dataService from '../../services/dataService.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // loginCode: null,
    hasCheckedIn: false,
    hasBindedPhone: false,
    userInfo: {
      // avatar: 'https://oss.flashxsport.com/flashUpload/userAvatar/tmp_9f9db9b83b9f4155ee6d75ae8df4ffcb_1758479306778992.jpg',
      // nickName: '满山饭'
    }
  },

  bindPhone() {
    console.log('this.data', this.data);
    // console.log('binded?', this.hasBindedPhone);
    if (this.data.hasBindedPhone) {
      return;
    }

    const that = this;
    wx.login({
      success: (loginRes) => {
        wx.showModal({
          title: '请先绑定手机号',
          editable: true,
          placeholderText: '在此输入手机号',
          success(res) {
            if (res.confirm) {
              dataService.bindPhone(loginRes.code, res.content).then(resp => {
                // console.log('bind resp:', resp);
                if (resp.success) {
                  let info = {
                    openid: resp.data.openid,
                    avatar: resp.data.avatar,
                    nickname: resp.data.member_name,
                    phone: resp.data.phone
                  };
                  that.setData({ userInfo: info, hasBindedPhone: true });
                  wx.setStorageSync('openid', info.openid);
                  wx.setStorageSync('phone', res.content);
                  wx.setStorageSync('avatar', info.avatar);
                  wx.setStorageSync('nickname', info.nickname);
                  wx.setStorageSync('memberId', resp.data.member_id);
    
                  wx.showToast({
                    title: '登录成功',
                    icon: 'success'
                  })
                } else {
                  wx.showToast({
                    title: resp.message,
                    icon: 'error'
                  })
                }
                
              })
            }
          }
        })
      },
    })
  },

  openPointsHistory() {
    wx.navigateTo({
      url: '/pages/pointHistory/pointHistory',
    });
  },

  handleCheckin() {
    if (this.data.hasCheckedIn) {
      return;
    }

    if (!this.data.userInfo.openid) {
      return wx.showToast({
        title: '请先登录',
        icon: 'error'
      });
    }
    let that = this;
    wx.showLoading();
    dataService.checkIn().then(resp => {
      if (resp.code === 0) {
        wx.hideLoading();
        wx.showToast({
          title: '签到成功',
          icon: 'success'
        });
        that.setData({hasCheckedIn: true});
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    let info = {
      phone: wx.getStorageSync('phone'),
      openid: wx.getStorageSync('openid'),
      nickname: wx.getStorageSync('nickname'),
      avatar: wx.getStorageSync('avatar'),
    };
    this.setData({
      userInfo: info
    });
console.log('userInfo:', info);
    if (info.phone && info.openid) {
      console.log('binded.................');
      this.setData({hasBindedPhone: true});
    }
    //  else {
    //   wx.login({
    //     success: (res) => {
    //       this.setData({loginCode: res.code});
    //     },
    //   })
    // }

    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    console.log('show.....s..s.......');
    if (this.data.userInfo.openid) {
      dataService.getMyInfo().then(resp => {
        console.log('status:', resp);
        if (resp.code != 0) {
          console.log('error:', resp.message);
        } else {
          wx.setStorageSync('nickname', resp.data.nickname);
          wx.setStorageSync('avatar', resp.data.avatar);
          let info = {...that.data.userInfo};
          info.nickname = resp.data.nickname;
          info.avatar = resp.data.avatar;
          info.points = resp.data.points;
          that.setData({userInfo: info, hasCheckedIn: resp.data.checkInStatus});
        }
        // if (resp.data?.checkInStatus === -1) {
        //   // 服务器没找到对应的openid，删除本地保存的数据
        //   wx.removeStorageSync('phone');
        //   wx.removeStorageSync('openid');
        // }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})